package com.ben.chatroom.handler;

import com.ben.chatroom.common.cocurrent.CallbackTask;
import com.ben.chatroom.common.cocurrent.CallbackTaskScheduler;
import com.ben.chatroom.common.cocurrent.FutureTaskScheduler;
import com.ben.chatroom.common.entity.ProtoMsg;
import com.ben.chatroom.processer.LoginProcessor;
import com.ben.chatroom.session.LocalSession;
import com.ben.chatroom.session.SessionManage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author huangyijun
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<ProtoMsg.Message> {

  private final LoginProcessor loginProcessor;

  public LoginRequestHandler(LoginProcessor loginProcessor) {
    this.loginProcessor = loginProcessor;
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, ProtoMsg.Message msg) throws Exception {
    ProtoMsg.HeadType type = msg.getType();

    if(!loginProcessor.op().equals(type)) {
      super.channelRead(ctx, msg);
      return;
    }

    LocalSession localSession = new LocalSession(ctx.channel());


    //异步处理任务
    CallbackTaskScheduler.add(new CallbackTask<Boolean>() {

      @Override
      public Boolean execute() throws Exception {
        return loginProcessor.action(localSession, msg);
      }

      @Override
      public void onBack(Boolean isSuccess) {
        if(isSuccess) {
          log.info("登录成功: " + localSession.getUser());
        }
        else {
          loginFail(ctx, localSession);
        }
      }

      @Override
      public void onException(Throwable e) {
        loginFail(ctx, localSession);
      }
    });

  }


  private void loginFail(ChannelHandlerContext ctx, LocalSession session) {
    log.error("登录失败:" + session.getUser());
    SessionManage.inst().closeSession(ctx);
  }

}
